package com.supor.aiot.home.ui.device;

import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.DialogUtils;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.android.baseconfig.common.views.CustomTitleBar;
import com.supor.aiot.common.analysis.AnalysisTool;
import com.supor.aiot.common.analysis.event.BindFailureEvent;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.base.BaseNfcActivity;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.entity.RecordBean;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.helper.NFCHelper;
import com.supor.aiot.home.R;
import com.supor.aiot.home.R2;
import com.supor.aiot.home.utils.PopUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.functions.Consumer;

import static com.supor.aiot.common.app.Constants.REQUEST_CODE;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: NFC配网引导页 <br>
 * 作者: lei <br>
 * 日期: 2020/12/8 <br>
 */
public class AddNFCDeviceActivity extends BaseNfcActivity {
    @BindView(R2.id.toolbar)
    protected CustomTitleBar toolbar;
    @BindView(R2.id.tv_step1)
    TextView tvStep1;
    @BindView(R2.id.ll_root)
    View llRoot;
    @BindView(R2.id.ll_gif)
    LinearLayout llGif;
    @BindView(R2.id.ll_nfc_tip)
    LinearLayout llNfcTip;
    @BindView(R2.id.tv_nfc_touch_tip)
    TextView tvNfcTouchTip;
    @BindView(R2.id.iv_nfc_area)
    ImageView ivNfcArea;


    private AppBasicDialog failureDialog;
    String ssid = null;
    String bssid = null;
    String pass = null;
    private RecordBean recordBean;
    private ProductType.ProductModel productModel;

    @Override
    protected int resourceId() {
        return R.layout.activity_add_nfc_device;
    }

    @Override
    public void initData() {
        super.initData();
        Intent intent = getIntent();
        if (intent != null) {
            productModel = (ProductType.ProductModel) intent.getSerializableExtra(Constants.Key.PRODUCT_MODEL);
            if (productModel == null) {
                Logc.d(TAG, "iotDevice is null");
                finish();
            }
        }
        PopUtils.getInstance().initNFCPop(this);
        if (!AppAgent.isLogin()) {
            SuporPresenter.getInstance().getCmccHelper().displayLogin(false);
        }
        processNFC();
    }

    public void initView() {
        super.initView();
        toolbar.setIvLeftOnClickListener(v -> finish());
        toolbar.setTvLeftOnClickListener(v -> finish());
        LinearLayout.LayoutParams llGifLayoutParams =
                (LinearLayout.LayoutParams) llGif.getLayoutParams();
        LinearLayout.LayoutParams nfcTipLayoutParams =
                (LinearLayout.LayoutParams) llNfcTip.getLayoutParams();
        LinearLayout.LayoutParams touchTipLayoutParams =
                (LinearLayout.LayoutParams) tvNfcTouchTip.getLayoutParams();
        if (AppAgent.smallScreen) {
            llGifLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_8);
            nfcTipLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_8);
            touchTipLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_5);
            touchTipLayoutParams.bottomMargin = getResources().getDimensionPixelSize(R.dimen.dp_10);
            ivNfcArea.setImageResource(R.mipmap.ic_nfc_area);
        } else {
            llGifLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_19);
            nfcTipLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_24);
            touchTipLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.dp_13);
            touchTipLayoutParams.bottomMargin = getResources().getDimensionPixelSize(R.dimen.dp_20);
            ivNfcArea.setImageResource(R.mipmap.ic_nfc_area);
        }
        llGif.setLayoutParams(llGifLayoutParams);
        llNfcTip.setLayoutParams(nfcTipLayoutParams);
        tvNfcTouchTip.setLayoutParams(touchTipLayoutParams);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            ssid = bundle.getString(Constants.Key.SSID);
            bssid = bundle.getString(Constants.Key.BSSID);
            pass = bundle.getString(Constants.Key.PASS);
            Logc.i("NFC ssid= " + ssid + ", bssid= " + bssid + ", pass= " + pass);
        }

        String tip = getString(R.string.bind_nfc_guide_step);
        SpannableString ss1 = new SpannableString(tip);

        int index1 = tip.indexOf("碰一碰");
        int index2 = tip.indexOf("碰一碰，更多菜");
        ss1.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                index1 - 1, index1 + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss1.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                index2 - 1, index2 + 8,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvStep1.setText(ss1);

        RxBus3.getInstance().register(Constants.Tag.LOGIN, (Consumer<String>) s -> {
            if (Constants.Value.CANCEL.equalsIgnoreCase(s)) {
                ToastUtils.getInstance().showCustomToast("请先登录");
            }
        }, this.getClass());
    }



    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (!PopUtils.getInstance().isNFCPopShow()) {
            return;
        }
        recordBean = NFCHelper.getInstance().processIntent(intent);
        if (recordBean != null) {
            if (recordBean.getProductId() == null) {
                ToastUtils.getInstance().showCustomToast("未获取到产品ID");
                Logc.e("onNewIntent: can't read productId");
                return;
            }
            // todo modify by lei  2021/09/25
            /*if (!recordBean.getProductId().equalsIgnoreCase(productModel.pid)) {
                ToastUtils.getInstance().showCustomToast("机器型号不匹配");
                Logc.e("onNewIntent: product not match");
                return;
            }

            if (productModel.classify == 1) {
                productModel.sn = recordBean.getSn();
                productModel.label = "一机多用，养生得心应手";
                productModel.newRecipe = "银耳汤上新啦～";
                DataCache.cacheDevice(productModel);
                PopUtils.getInstance().touchSuccess();
                new Handler().postDelayed(this::jumpToNextActivity, 2700);
            }*/
        } else {
            Logc.e(TAG, "record read failed");
            analysisBindFailure(BindFailureEvent.Value.REASON_RECORD);
            showNFCFailureDialog();
        }
    }

    private void showNFCFailureDialog() {
        PopUtils.getInstance().dismissNFCPop();
        if (failureDialog != null) {
            if (failureDialog.isShowing()) {
                return;
            } else {
                failureDialog.show();
            }
            return;
        }
        failureDialog = DialogUtils.simpleShowDialog(this, R.string.nfc_touch_failure,
                R.string.nfc_touch_failure_tip, R.string.sure);
        failureDialog.setCancelable(false);
        failureDialog.show();
    }

    @OnClick({R2.id.btn_next_step, R2.id.btn_cancel})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.btn_next_step) {
            if (!AppAgent.isLogin()) {
                SuporPresenter.getInstance().getCmccHelper().displayLogin(false);
                return;
            }
            PopUtils.getInstance().showNFCPop(this, llRoot);
        } else if (view.getId() == R.id.btn_cancel) {
            setResult(10);
            finish();
        }
    }

    private void jumpToNextActivity() {
        setResult(Constants.RESULT_CODE);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void analysisBindFailure(String reason) {
        HashMap<String, String> params = new HashMap<>();
        params.put(BindFailureEvent.Param.BIND_TYPE, BindFailureEvent.Value.BIND_TYPE_NFC);
        params.put(BindFailureEvent.Param.USER_ID, GlobalDataCache.userInfo.getBossUserId());
        params.put(BindFailureEvent.Param.WIFI_NAME, ssid);
        params.put(BindFailureEvent.Param.BIND_STAGE, BindFailureEvent.Value.STAGE_TOUCH);
        params.put(BindFailureEvent.Param.FAILURE_REASON, reason);
        AnalysisTool.bindFailureEvent(params, true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE == requestCode) {
            if (resultCode == 1) {
                setResult(1);
                finish();
            }
        }
    }
}
